var currentX = 0;
var currentY = 0;
var previousX = 0;
var previousY = 0;
var currentLineIdIndex ;
var currentLineGroup ;
var touchX;
var touchY;
var handlingGesture = false;
var initialScale = 0;
var initialAngle = 0;
var override_oldc_object = null;
var moving = false;
var hasArrowDef = false;
var marginTop = 75;
var marginLeft = 295;
function mousedown_listener(event) {
    if (distanceMeasurement) {
        mousedown_measure(event);
    } else {
        mousedown_action(event);
    }
}

function mouseup_listener(event) {
    if (distanceMeasurement) {
        mouseup_measure(event);
    } else {
        mouseup_action(event);
    }

}
function target_mouseup_listener(event) {
    target_mouseup_action(event);

}

function mousedblclick_listener(event) {
    event.preventDefault();
    var obj = svgCanvas.list[ svgCanvas.selectedObjectID ];
    utils.showDom('operate/parameter/'+templateId+"?iconId="+utils.getString(obj.iconId)+"&parameterId="+utils.getString(obj.parameterId)+"&iconName="+utils.getString(obj.iconName)+"&memo="+utils.getString(obj.memo),"parameterInfo",{title:obj.iconName});
}

function mousemove_listener(event) {
    moving = false;
    mousemove_action(event);
}

function touchStart(event) {
    event.preventDefault();
    if (!handlingGesture) {
        if (event.touches.length == 1) {
            mousedown_action(event);
        }
    }
}

function touchMove(event) {
    moving = false;
    event.preventDefault();
    if (!handlingGesture) {
        if (event.touches.length == 1) {
            mousemove_action(event);
        }
    }
}

function touchEnd(event) {
    if (event.touches.length == 0) {
        handlingGesture = false;
    }
    mouseup_action(event);
    moving = false;
}

function gestureStart(event) {
    event.preventDefault();
    handlingGesture = true;
    var oldc_object = findObject(event);
    var oldc_objectID = svgCanvas.selectedObjectID;
    if (moving && oldc_object.id != oldc_objectID) {
        oldc_objectID = oldc_object.id;
        svgCanvas.select(oldc_objectID);
        svgCanvas.toggleFocus();
    }
    initialScale = svgCanvas.list[oldc_objectID].zoomRatio;
    initialAngle = svgCanvas.list[oldc_objectID].angle;

}

function gestureChange(event) {
    event.preventDefault();
    var oldc_objectID = svgCanvas.selectedObjectID;
    svgCanvas.list[oldc_objectID].zoomRatio = initialScale * event.scale;
    svgCanvas.list[oldc_objectID].angle = initialAngle + event.rotation;
    svgCanvas.transform(oldc_objectID);

}

function gestureEnd(event) {
    var oldc_objectID = svgCanvas.selectedObjectID;

    var zoomRatioValue = Math.round(svgCanvas.list[oldc_objectID].zoomRatio * 100) / 100;
    var angleValue = Math.round(svgCanvas.list[oldc_objectID].angle * 100) / 100

    $("#size_slider").slider("value", zoomRatioValue);
    $("#size_title").html("Size: " + zoomRatioValue);
    $("#angle_slider").slider("value", angleValue);
    $("#angle_title").html("Angle: " + angleValue);
}

function findObject(event) {
    var oldc_object = event.target;
    if (oldc_object instanceof HTMLFormElement) {
        return null;
    }
    if (oldc_object && oldc_object.id && oldc_object.id instanceof HTMLInputElement) {
        return null;
    }
    //resur find eventTarget 是不是 OLDC_Object 所有的id都是以OLDC_Object开始
    while (
        (oldc_object !== null) &&
        (((typeof oldc_object.id) != "undefined") &&
            !(oldc_object.id.match("^" + 'OLDC_Object') == 'OLDC_Object'))
        ) {
        oldc_object = oldc_object.parentNode;
        if (oldc_object.id instanceof HTMLElement) {
            return null;
        }
    }
    return oldc_object;
}

function mousedown_measure(evt) {
    evt = evt || window.event;
    var isTouch = false;
    if (typeof evt.touches != 'undefined') {
        var evtObject = evt.touches[0];
    }else{
        var evtObject = evt;
    }
    svgCanvas.clearSelection();
    if (isTouch) {
        previousX = evtObject.pageX;
        previousY = evtObject.pageY;
    }else{
        previousX = evtObject.clientX-marginLeft;
        previousY = evtObject.clientY-marginTop;
        console.log({x:evtObject.clientX, y:evtObject.clientY})
        console.log({previousX, previousY})
        currentLineGroup = svgCanvas.svg.group({stroke: 'red', strokeWidth: 1});
        currentLineIdIndex = svgCanvas.addLineObject(currentLineGroup,lineType);
        svgCanvas.svg.circle(currentLineGroup,previousX, previousY, 4,
            {fill: 'none',id:'OLDC_Circle_'+currentLineGroup.id});
        // // document.addEventListener("mousemove", mousemove_listener, true);
        document.addEventListener("mouseup", mouseup_listener, true);
    }

}
function mousedown_action(evt) {
    evt = evt || window.event;
    var isTouch = false;

    if (typeof evt.touches != 'undefined') {
        var evtObject = evt.touches[0];
        isTouch = true;
    } else {
        var evtObject = evt;
    }
    //zhaoyf 找到事件的target
    var oldc_object = findObject(evt);
    // let liTargets = $(event.target).parents("li[class*='iconTarget']");
    // if (liTargets.length > 0) {
    //     document.addEventListener("mouseup", target_mouseup_listener, true);
    //     return;
    // }
    //如果target不是OLDC_Object 返回
    if (oldc_object === null || (typeof oldc_object.id) == "undefined") {
        return; // don't move
    }
    //先清理一下
    actionHistory.clear();
    if (svgCanvas.list[oldc_object.id].isAClone) {
        actionHistory.push(svgCanvas.list[oldc_object.id], 'move');
    }else{
        actionHistory.markClone();
    }

    if (isTouch) {
        previousX = evtObject.pageX;
        previousY = evtObject.pageY;
    } else {
        previousX = evt.clientX;
        previousY = evt.clientY;

        document.addEventListener("mousemove", mousemove_listener, true);
        document.addEventListener("mouseup", mouseup_listener, true);
    }

    if (!override_oldc_object) {
        if (svgCanvas.list[oldc_object.id].isAClone) {
            svgCanvas.select(oldc_object.id);
            svgCanvas.toggleFocus();
        } else {
            if (svgCanvas.hasFocusedObject) {
                svgCanvas.clearSelection();
                svgCanvas.toggleFocus();
            }
        }
    }

}

function mouseup_action(evt) {
    var oldc_objectID = svgCanvas.selectedObjectID;
    evt = evt || window.event;

    var isTouch = false;
    if (typeof evt.touches != 'undefined') {
        isTouch = true;
    }

    var oldc_object = findObject(evt);

    if (oldc_object === null || (typeof oldc_object.id) == "undefined") {
        return; // don't move
    }
    override_oldc_object = null;

    if (!isTouch) {
        document.removeEventListener("mousemove", mousemove_listener, true);
        document.removeEventListener("mouseup", mouseup_listener, true);
    }

}
function target_mouseup_action(event) {
    let liTargets = $(event.target).parents("li[class*='iconTarget']");
    if (liTargets.length > 0) {
        // console.log(event.target);
    }
    document.removeEventListener("mouseup", target_mouseup_listener, true);
}

function mouseup_measure(evt) {
    evt = evt || window.event;
    var oldc_objectID = svgCanvas.selectedObjectID;

    evt = evt || window.event;

    var isTouch = false;
    if (typeof evt.touches != 'undefined') {
        var evtObject = evt.touches[0];
        isTouch = true;
    }else{
        var evtObject = evt;
    }

    if (!isTouch) {
        document.removeEventListener("mousemove", mousemove_listener, true);
        document.removeEventListener("mouseup", mouseup_listener, true);
    }
    currentX = evtObject.clientX-marginLeft;
    currentY = evtObject.clientY-marginTop;
    var distance = utils.GetDistance(previousX,previousY,currentX,currentY);
    if (!hasArrowDef &&lineType == 'arrow') {
        hasArrowDef = true;
        var defs = svgCanvas.svg.defs('arrowDef');
        var marker = svgCanvas.svg.marker(defs, 'arrowMarker', 5, 5, 10, 10,'auto-start-reverse',{stroke:"#020102", fill:"#020102"});
        var arrowPath = svgCanvas.svg.createPath();
        svgCanvas.svg.path(marker, arrowPath.move(0, 0).line(10,5).line(0,10).close());
    }
    var path = svgCanvas.svg.createPath();
    if (lineType == 'arrow') {
        svgCanvas.svg.path(currentLineGroup, path.move(previousX, previousY).line(currentX,currentY),
            {fill: 'none', stroke: '#020102', strokeWidth: 2,id:'path_'+currentLineGroup.id,"marker-end":"url(#arrowMarker)"});
    }else{
        svgCanvas.svg.path(currentLineGroup, path.move(previousX, previousY).line(currentX,currentY),
            {fill: 'none', stroke: '#020102', strokeWidth: 2,id:'path_'+currentLineGroup.id});
    }

    $("circle").remove();
    var texts = svgCanvas.svg.createText();
    var text = svgCanvas.svg.text(currentLineGroup,'');
    svgCanvas.svg.textpath(text, '#path_'+currentLineGroup.id, texts.string(distance),{startOffset:'20%',strokeWidth:0.5,stroke:'red'});
    svgCanvas.list[currentLineGroup.id].left_x = previousX;
    svgCanvas.list[currentLineGroup.id].left_y = previousY;
    svgCanvas.list[currentLineGroup.id].right_x = currentX;
    svgCanvas.list[currentLineGroup.id].right_y = currentY;
    svgCanvas.list[currentLineGroup.id].memo = distance;
    actionHistory.clear();
    actionHistory.push(svgCanvas.list[currentLineGroup.id], 'new');
    lineType = null;
    distanceMeasurement = false;
    $(".line").attr("checked", false);
}
function mousemove_measure(evt) {
    evt = evt || window.event;
    var oldc_objectID = svgCanvas.selectedObjectID;
    evt = evt || window.event;

    var isTouch = false;
    if (typeof evt.touches != 'undefined') {
        isTouch = true;
    }


    if (!isTouch) {
        document.removeEventListener("mousemove", mousemove_listener, true);
        document.removeEventListener("mouseup", mouseup_listener, true);
    }

}

function mousemove_action(evt) {
    evt = evt || window.event;

    // Focus set on the object being moved
    svgCanvas.toggleFocus();

    var isTouch = false;
    if (typeof evt.touches != 'undefined') {
        var evtObject = evt.touches[0];
        isTouch = true;
    } else {
        var evtObject = evt;
    }

    var oldc_object = findObject(evt);

    if (!svgCanvas.selectedObjectID) var oldc_objectID = oldc_object.id
    else var oldc_objectID = svgCanvas.selectedObjectID;
    if ((typeof (svgCanvas.list[oldc_objectID]) != "undefined"
            && !svgCanvas.list[oldc_objectID].isAClone
        )
        || oldc_object === null
        || (typeof oldc_objectID) == "undefined"
    ) {
        if ((typeof oldc_objectID) != "undefined") {
            svgCanvas.setSelectedMenuObject(oldc_objectID);
        }
        if (!svgCanvas.list[oldc_object.id].isAClone) {
            override_oldc_object = svgCanvas.duplicate(oldc_objectID);
            svgCanvas.select(override_oldc_object.id);
            actionHistory.push(svgCanvas.list[override_oldc_object.id], 'new');
//            oldc_objectID = svgCanvas.selectedObjectID;
        }
        return; // don't move
    }

    if (isTouch) {
        currentX = evtObject.pageX;
        currentY = evtObject.pageY;
    } else {
        currentX = evtObject.clientX;
        currentY = evtObject.clientY;
    }
    console.log({previousX,currentX,previousY,currentY})
    svgCanvas.transform(oldc_objectID, (currentX - previousX), (currentY - previousY));

    if (isTouch) {
        previousX = evtObject.pageX;
        previousY = evtObject.pageY;
    } else {
        previousX = evtObject.clientX;
        previousY = evtObject.clientY;
    }
    svgCanvas.list[oldc_object.id].currentX = currentX;
    svgCanvas.list[oldc_object.id].currentY = currentY;

    return;
}
